import { defineStore } from "pinia";
import { ref } from "vue";

export const useOrdersStore = defineStore("orders", () => {
  const state = ref({
    ordersList: [],
    initialOrderList: [],
  });
  const getter = {
    getOrderDetail(orderId) {
      return state.value.ordersList.find((obj) => obj.id == orderId);
    },
  };
  const actions = {
    async setOrderList(orderList) {
      state.value.ordersList = orderList;
      sessionStorage.setItem("order", JSON.stringify(orderList));
    },
    async setInitialOrderList(orderList) {
      state.value.initialOrderList = orderList;
      sessionStorage.setItem("initialOrder", JSON.stringify(orderList));
    },
    async setOrder(orderInfo) {
      const index = state.value.ordersList.findIndex(
        (order) => order.id === orderInfo.id
      );
      if (index != -1) {
        state.value.ordersList[index] = Object.assign(
          {},
          state.value.ordersList[index],
          orderInfo
        );
        sessionStorage.setItem("order", JSON.stringify(state.value.ordersList));
      } else {
        console.warn(`Order with ID ${orderInfo.id} not found in ordersList.`);
      }
    },
  };
  return { state, getter, actions };
});
